package com.tuzhi.sys.scurity;

import com.tuzhi.security.service.impl.SecurityConfigImpl;
import com.tuzhi.sys.jpa.entity.SysMenuEntity;
import com.tuzhi.sys.service.SysMenuService;
import com.tuzhi.util.StringTzUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.List;

@Primary
@Component
public class MySecurityConfigImpl extends SecurityConfigImpl {
    private static final Logger log = LoggerFactory.getLogger(MySecurityConfigImpl.class);

    @Value("${security.anonUrl}")
    private String anonUrl;

   // @Value("${security.authUrl}")
    @Value("${security.authUrl}")
    private String authUrl;

    @Autowired
    private SysMenuService sysMenuService;


    public void setPermitList() {
        str2List(permitList, anonUrl);
        log.warn("加载的配置 permitList 如下：");
        for (String url : permitList) {
            log.warn(url);
        }
    }

    public void setInterceptList() {
        str2List(interceptList, authUrl);
        log.warn("加载的配置 interceptList 如下：");
        for (String url : interceptList) {
            log.warn(url);
        }

    }

    public void setGrantedAuthorityList() {
        List<SysMenuEntity> list = sysMenuService.loadAllSysMenu();
        grantedAuthorityList.clear();
        for (SysMenuEntity entity : list) {
            grantedAuthorityList.add(entity.getPerms());
        }

    }

    /**
     * 把配置文件中的字符串转换成list,去除前后空格
     *
     * @param targetList
     * @param strs
     */
    private void str2List(List<String> targetList, String strs) {
        if (StringUtils.isNotEmpty(strs)) {
            List<String> authUrls = StringTzUtil.splitList(strs, ",");
            for (String url : authUrls) {
                if (targetList.contains(url)) {
                    continue;
                }
                targetList.add(StringUtils.trim(url));
            }
        }
    }

}
